package main

import (
	"fmt"
	"goissue/util/ghttp"
	"log"
	"os"
	"path"
	"strconv"
	"strings"

	"github.com/xuri/excelize/v2"
)

type IssueRequest struct {
	Title       string `json:"title"`
	Description string `json:"description"`
}

type AddIssueRes struct {
	Iid     int    `json:"iid"`
	Code    string `json:"code"`
	Message string `json:"message`
}

func main() {
	if len(os.Args) != 4 {
		fmt.Println("参数错误，请根据 README.md 正确传参")
		return
	}

	accessToken := os.Args[1]
	exterprisePath := os.Args[2]
	filePath := os.Args[3]
	namespaces := ""
	fmt.Println("导入开始")
	f, err := excelize.OpenFile(filePath)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		// Close the spreadsheet.
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()
	for _, sheet := range f.GetSheetList() {
		// 存在则继续
		isOk, _ := f.GetSheetVisible(sheet)
		if isOk {
			// 读取数据
			rows, err := f.GetRows(sheet)
			if err != nil {
				fmt.Println(err)
				return
			}
			for rowIndex, row := range rows {
				if len(row) == 0 {
					continue
				}
				if rowIndex < 2 {
					continue
				}
				if len(row[3]) == 0 || len(row[1]) == 0 || len(row[2]) == 0 {
					fmt.Println("第", strconv.Itoa(rowIndex+1), "行参有误，「编码，标题, 描述，代码仓库地址」必填")
					continue
				}
				i, _ := strconv.Atoi(row[4])
				if i > 0 {
					continue
				}

				// 拼装数据
				title := row[0] + ":" + row[1]
				if len(title) > 100 {
					fmt.Println("标题不能超过 100")
					continue
				}
				body := row[2]
				projectPath := row[3]

				projectUrl := strings.Split(projectPath, "/")
				ownerPath := projectUrl[3]
				repoPath := projectUrl[4]

				repoValidate, newGroup := Validate(ownerPath, repoPath, exterprisePath, accessToken, namespaces)
				if !repoValidate {
					fmt.Println("参数校验错误：exterprisePath不一致")
					continue
				}
				if newGroup {
					namespaces = ownerPath
				}
				number := Post(title, body, ownerPath, repoPath, accessToken)
				fmt.Println(sheet, "E", strconv.Itoa(rowIndex+1), number)
				f.SetCellValue(sheet, "E"+strconv.Itoa(rowIndex+1), number)
				if err = f.Save(); err != nil {
					fmt.Println(err)
				}
			}
		}
	}
	fmt.Println("导入完成")
}

func Validate(ownerPath, repoPath, exterprisePath, accessToken, namespaces string) (bool, bool) {
	if ownerPath == exterprisePath {
		return true, false
	}
	return false, true
}

func Post(title, body, ownerPath, repoPath, accessToken string) int {
	// 替换 {owner} 为实际的仓库所有者用户名
	owner := path.Join(ownerPath, repoPath)
	// 构建请求URL
	url := fmt.Sprintf("https://api.gitcode.com/api/v4/projects/%s/issues", owner)

	// 创建一个 IssueRequest 结构体实例
	issueData := IssueRequest{
		Title:       title,
		Description: body,
	}

	req := ghttp.Request{
		Method:      "POST",
		Url:         url,
		ContentType: "application/json",
		Body:        issueData,
	}
	req.AddHeader("private-token", accessToken)
	resp, err := req.Do()
	if err != nil {
		fmt.Println("接口请求失败，原因：", err.Error())
		os.Exit(1)
	}
	defer resp.Body.Close()
	var issueRes AddIssueRes
	resp.Body.FromToJson(&issueRes)
	if len(issueRes.Message) > 0 {
		fmt.Println("导入失败，原因：", issueRes.Message)
		os.Exit(1)
	}
	return issueRes.Iid
}
